package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.TradeTrademarkCategoryUserRefundBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.function.DimAsyncFunction;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2022/7/29 14:59
 */
public class Dws_11_DwsTradeTrademarkCategoryUserRefundWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_11_DwsTradeTrademarkCategoryUserRefundWindow().init(
            3011,
            2,
            "Dws_11_DwsTradeTrademarkCategoryUserRefundWindow",
            Constant.TOPIC_DWD_TRADE_ORDER_REFUND
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> beanStream = stream
            .map(str -> {
                JSONObject obj = JSON.parseObject(str);
                
                return TradeTrademarkCategoryUserRefundBean.builder()
                    .skuId(obj.getString("sku_id"))
                    .userId(obj.getString("user_id"))
                    .orderIdSet(new HashSet<>(Collections.singleton(obj.getString("order_id"))))
                    .ts(obj.getLong("ts") * 1000)
                    .build();
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeTrademarkCategoryUserRefundBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
            );
        
        //补充需要分组的维度信息
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> streamWithKeyByDim = AsyncDataStream.unorderedWait(
            beanStream,
            new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
                @Override
                public String getTable() {
                    return "dim_sku_info";
                }
                
                @Override
                public String getId(TradeTrademarkCategoryUserRefundBean input) {
                    return input.getSkuId();
                }
                
                @Override
                public void addDim(TradeTrademarkCategoryUserRefundBean input, JSONObject dim) {
                    input.setTrademarkId(dim.getString("TM_ID"));
                    input.setCategory3Id(dim.getString("CATEGORY3_ID"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
    
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> aggregatedStream = streamWithKeyByDim
            .keyBy(bean -> bean.getUserId() + "_" + bean.getTrademarkId() + "_" + bean.getCategory3Id())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    public TradeTrademarkCategoryUserRefundBean reduce(TradeTrademarkCategoryUserRefundBean bean1,
                                                                       TradeTrademarkCategoryUserRefundBean bean2) throws Exception {
                    
                        bean1.getOrderIdSet().addAll(bean2.getOrderIdSet());
                        return bean1;
                    }
                },
                new ProcessWindowFunction<TradeTrademarkCategoryUserRefundBean, TradeTrademarkCategoryUserRefundBean, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<TradeTrademarkCategoryUserRefundBean> elements,
                                        Collector<TradeTrademarkCategoryUserRefundBean> out) throws Exception {
                    
                        TradeTrademarkCategoryUserRefundBean bean = elements.iterator().next();
                    
                        bean.setStt(AtguiguUtil.toDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDateTime(ctx.window().getEnd()));
                    
                        bean.setRefundCount((long) bean.getOrderIdSet().size());
                    
                        bean.setTs(System.currentTimeMillis());
                    
                        out.collect(bean);
                    
                    }
                }
            );
    
    
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> tmStream = AsyncDataStream.unorderedWait(
            aggregatedStream,
            new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
                @Override
                public String getTable() {
                    return "dim_base_trademark";
                }
            
                @Override
                public String getId(TradeTrademarkCategoryUserRefundBean input) {
                    return input.getTrademarkId();
                }
            
                @Override
                public void addDim(TradeTrademarkCategoryUserRefundBean input, JSONObject dim) {
                    input.setTrademarkName(dim.getString("TM_NAME"));
                }
            },
            60,
            TimeUnit.SECONDS
        );
    
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> c3Stream = AsyncDataStream.unorderedWait(
            tmStream,  // 要异步处理的流
            new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category3";
                }
            
                @Override
                public String getId(TradeTrademarkCategoryUserRefundBean input) {
                    return input.getCategory3Id();
                }
            
                @Override
                public void addDim(TradeTrademarkCategoryUserRefundBean input, JSONObject dim) {
                    input.setCategory3Name(dim.getString("NAME"));
                    // 查询c2_id
                    input.setCategory2Id(dim.getString("CATEGORY2_ID"));
                }
            },
            60,   // 异步处理超时时间
            TimeUnit.SECONDS  // 超时赶时间的单位
        );
    
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> c2Stream = AsyncDataStream.unorderedWait(
            c3Stream,  // 要异步处理的流
            new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category2";
                }
            
                @Override
                public String getId(TradeTrademarkCategoryUserRefundBean input) {
                    return input.getCategory2Id();
                }
            
                @Override
                public void addDim(TradeTrademarkCategoryUserRefundBean input, JSONObject dim) {
                    input.setCategory2Name(dim.getString("NAME"));
                    // 查询c2_id
                    input.setCategory1Id(dim.getString("CATEGORY1_ID"));
                }
            },
            60,   // 异步处理超时时间
            TimeUnit.SECONDS  // 超时赶时间的单位
        );
    
    
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> streamWithAllDim = AsyncDataStream.unorderedWait(
            c2Stream,  // 要异步处理的流
            new DimAsyncFunction<TradeTrademarkCategoryUserRefundBean>() {
                @Override
                public String getTable() {
                    return "dim_base_category1";
                }
            
                @Override
                public String getId(TradeTrademarkCategoryUserRefundBean input) {
                    return input.getCategory1Id();
                }
            
                @Override
                public void addDim(TradeTrademarkCategoryUserRefundBean input, JSONObject dim) {
                    input.setCategory1Name(dim.getString("NAME"));
                }
            },
            60,   // 异步处理超时时间
            TimeUnit.SECONDS  // 超时赶时间的单位
        );
        
        streamWithAllDim.addSink(FlinkSinkUtil.getClickHouseSink("dws_trade_trademark_category_user_refund_window", TradeTrademarkCategoryUserRefundBean.class));
    }
}
/*

交易域品牌-品类-用户粒度退单各窗口汇总表

数据源:
    交易域退单事务事实表

粒度:
     sku
     
     聚合维度:
       品牌品类用户
       
      在聚合之前先根据 sku_id 找到 品牌id和品类id , 然后再去 品牌品类用户 keyBy
      
      
      聚合后, 再去join剩下的维度
      
      
 */